package com.liu.seckill.rabbitmq;

import com.liu.seckill.pojo.SeckillMessage;
import com.liu.seckill.pojo.User;
import com.liu.seckill.service.IGoodsService;
import com.liu.seckill.service.IOrderService;
import com.liu.seckill.util.JsonUtil;
import com.liu.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @ClassName MQReceiver
 * @Author ：name
 * @Date ：2022-02-18 10:33
 * @Description：
 * @Version: 1.0
 */
@Service
@Slf4j
public class MQReceiver {

    @Autowired
  private IGoodsService goodsService;
  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private IOrderService orderService;

    @RabbitListener(queues = "queue_fanout01")
  public void receive01(Object msg) {
   log.info("QUEUE01接受消息：" + msg);
  }

    @RabbitListener(queues = "queue_fanout02")
  public void receive02(Object msg) {
   log.info("QUEUE02接受消息：" + msg);
  }

  @RabbitListener(queues = "queue_direct01")
    public void receive03(Object msg){

      log.info("QUEUE03接受消息：" + msg);

  }

  @RabbitListener(queues = "queue_direct02")
    public void receive04(Object msg){
      log.info("QUEUE04接受消息：" + msg);
  }

  @RabbitListener(queues = "queue_topic01")
  public void receive05(Object msg){
    log.info("QUEUE05接受消息：" + msg);
  }

  @RabbitListener(queues = "queue_header01")
  public void receive06(Message message){
    log.info("QUEUE01接受Message对象：" + message);
    log.info("QUEUE01接受消息：" + new String(message.getBody()));

  }

  @RabbitListener(queues = "queue_header02")
  public void receive07(Message message) {
    log.info("QUEUE02接受Message对象：" + message);
    log.info("QUEUE02接受消息：" + new String(message.getBody()));
  }

  @RabbitListener(queues = "seckillQueue")
  public void receive(String msg) {

    log.info("QUEUE接受消息：" + msg);
    SeckillMessage message = JsonUtil.jsonStr2Object(msg, SeckillMessage.class);
    Long goodId = message.getGoodId();
    User user = message.getUser();
    GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodId);
    //判断库存
    if(goods.getStockCount()<1){
      return;
    }
    String seckillOrderJson=(String) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId);
     if (!StringUtils.isEmpty(seckillOrderJson)) {
     return;
   }

   orderService.seckill(user, goods);



  }

}
